﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.NetworkInformation;

namespace OpenLigaDB.DataBrowser
{
    public partial class MainPage : UserControl
    {
        OpenLigaDBWebservice.SportsdataSoapClient oldbClient;
        int? _currentGroupOrderID;

        public MainPage()
        {
            App.Current.CheckAndDownloadUpdateCompleted += new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted);
            App.Current.CheckAndDownloadUpdateAsync();

            InitializeComponent();
            oldbClient = new OpenLigaDBWebservice.SportsdataSoapClient();
        }

        void Current_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            if (e.UpdateAvailable)
                MessageBox.Show("Neue Version verfügbar. Anwendung bitte neu starten");
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            GetApplicationState();
            BindLeagueList();
        }
        void BindLeagueList()
        {
            try
            {
                lblState.Content = "Liga-Liste wird geladen...";

                oldbClient.GetAvailLeaguesCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        cbxLeagues.ItemsSource = e.Result.Where(x => x.leagueSaison == "2010" || x.leagueSaison == "2009");
                        lblState.Content = "";

                    }
                    else
                    {
                        lblState.Content = "Fehler!";
                    }
                };
                oldbClient.GetAvailLeaguesAsync();
            }
            catch (Exception ex)
            {
                lblState.Content = "Fehler!";

            }

        }

        void GetCurrentGroupOrderId()
        {

            oldbClient.GetCurrentGroupOrderIDCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        _currentGroupOrderID = e.Result;
                        FillMatchList();
                    }
                    else
                    {
                        lblState.Content = "Fehler beim Ermitteln des aktuellen Spieltages!";

                    }
                };
            oldbClient.GetCurrentGroupOrderIDAsync((cbxLeagues.SelectedItem as OpenLigaDBWebservice.League).leagueShortcut);
        }

        private void cbxLeagues_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            GetCurrentGroupOrderId();
        }

        void FillMatchList()
        {
            lblState.Content = "Spiele werden geladen...";

            oldbClient.GetMatchdataByGroupLeagueSaisonCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        if (e.Result.Any())
                        {


                            var matchData = e.Result.ToList();
                            wrpMatches.Children.Clear();

                            foreach (var item in matchData)
                            {
                                var listItem = new Controls.MatchItem();
                                listItem.lblDate.Content = item.matchDateTime.ToString();
                                listItem.lblTeamName1.Content = item.nameTeam1;
                                listItem.lblTeamName2.Content = item.nameTeam2;
                                listItem.lblLoc.Content = item.location.locationStadium != null ? item.location.locationStadium + ", Zuschauer: " + item.NumberOfViewers.ToString() : "";


                                if (item.matchResults != null)
                                {
                                    if (item.matchResults.Any())
                                    {
                                        var results = from r in item.matchResults
                                                      orderby r.resultOrderID
                                                      select r;

                                        var resultList = new List<Models.Result>();
                                        foreach (var result in results)
                                        {
                                            resultList.Add(new Models.Result { ResultText = result.pointsTeam1.ToString() + " : " + result.pointsTeam2.ToString(), ResultType = result.resultName });
                                        }
                                        listItem.dgdResults.ItemsSource = resultList;
                                    }

                                }

                                wrpMatches.Children.Add(listItem);
                            }
                            lblState.Content = "Fertig!";

                        }
                        else
                        {
                            lblState.Content = "Keine Daten vorhanden!";
                        }
                    }
                };
            oldbClient.GetMatchdataByGroupLeagueSaisonAsync(_currentGroupOrderID.Value - 1, (cbxLeagues.SelectedItem as OpenLigaDBWebservice.League).leagueShortcut, (cbxLeagues.SelectedItem as OpenLigaDBWebservice.League).leagueSaison);
        }

        private void GetApplicationState()
        {
            lblAppState.Content = NetworkInterface.GetIsNetworkAvailable() ? "Netzwerkverbindung OK!" : "keine Netzwerkverbindung vorhanden!";
            //lblAppState.Content+= App.Current.IsRunningOutOfBrowser ? " installiert" : " im Browser";
        }
    }
}
